package activator;

import java.util.Dictionary;
import java.util.Hashtable;

import library.service.LibraryService;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;

import service.library.OsgiLibraryServiceImpl;
import service.managed.ManagedServiceLib;

public class Activator implements BundleActivator {
	private static final String LIB_SERVICE_PID = "library.service.pid";

	ServiceRegistration libraryServiceReg;

	ServiceRegistration managedServiceLibReg;

	// --- BundleActivator interface implementation ----------------------------
	public void start(BundleContext context) throws Exception {
		System.out.println("REGISTRATOR: start() method");

		LibraryService libraryService = new OsgiLibraryServiceImpl();
		libraryServiceReg = context.registerService(
				LibraryService.class.getName(), libraryService, null);

		System.out.println("REGISTRATOR: LibraryService registered.");

		// TEST 1
		// System.out.println("REGISTRATOR: Set LibraryService=null.");
		// libraryService = null;

		// TEST 2
		// System.out.println("REGISTRATOR: LibraryService UNREGISTER");
		// libraryServiceReg.unregister();

		// MANAGED SERVICE

		Dictionary mngServiceProps = new Hashtable(2);
		mngServiceProps.put(Constants.SERVICE_PID, LIB_SERVICE_PID);
		mngServiceProps.put("name", "Library Service Configuration");

		ManagedService managedServiceLib = new ManagedServiceLib(libraryService);
		managedServiceLibReg = context.registerService(
				ManagedService.class.getName(), managedServiceLib, mngServiceProps);

	}

	public void stop(BundleContext context) throws Exception {

		if (libraryServiceReg != null) {
			libraryServiceReg.unregister();
			libraryServiceReg = null;
		}

		if (managedServiceLibReg != null) {
			managedServiceLibReg.unregister();
			managedServiceLibReg = null;
		}

	}

}
